package com.tramy.hpush.server;

import com.tramy.hpush.server.data.ClientAuthInfo;
import com.tramy.hpush.server.data.Message;
import com.tramy.hpush.server.data.PushResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class Sender {

    public static final Log logger = LogFactory.getLog(Sender.class);

    private static final long PERIOD = 45 * 60 * 1000;

    private final String appId;
    private final String appSecret;

    private ClientAuthInfo authInfo;

    public Sender(String appId, String appSecret) {
        this.appId = appId;
        this.appSecret = appSecret;

        refreshAccessToken();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                refreshAccessToken();
            }
        }, PERIOD, PERIOD);
    }

    private void refreshAccessToken() {
        try {
            ClientAuthInfo authInfo = OkHttpUtils
                    .requestAccessToken(appId, appSecret);

            this.authInfo = authInfo;
            logger.info("【HPUSH SDK】accessToken已更新为" + authInfo.getAccessToken() + ",类型：" + authInfo.getTokenType());
        }catch (IOException e) {
            logger.error("【HPUSH SDK】accessToken更新失败");
        }
    }

    public PushResponse send(Message message) throws IOException {
        return OkHttpUtils.sendPushData(appId, authInfo,
                false, message);
    }

    public PushResponse send(Message message, boolean isDebug) throws IOException {
        return OkHttpUtils.sendPushData(appId, authInfo,
                isDebug, message);
    }

}
